package com.hzit.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 类名：
 * 作者：WF
 * 功能：mybatis访问的工具类，得到SqlSession
 */
public class MySqlSessionFactory {
	/**
	 * 1. 获取SqlSessionFactory
	 * @return
	 * @throws IOException
	 */
	private static SqlSessionFactory getSqlSessionFactroy() throws IOException {
		String resource = "mybatis/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		return sqlSessionFactory;
	}

	/**
	 * 2. 获取SqlSession对象
	 * @param autoCommit 是否自动提交 true: 代表自动提交(适用于增、删、改) false:不自动提交(只适用于查询)
	 * @return
	 * @throws IOException
	 */
	public static SqlSession getSqlSession(boolean autoCommit) throws IOException {
		SqlSessionFactory sqlSessionFactroy = getSqlSessionFactroy();
		return sqlSessionFactroy.openSession(autoCommit);
	}
}
